<?php

namespace app\shb\controller;

use think\Controller;
use think\Db;
use think\Env;
use think\Exception;
use think\Request;

/**
 * 升话宝前台组合代码
 * Class Index
 * @package app\shb\controller
 */
class Index extends Controller
{
    protected $info = [];
    protected $user_info = [];
    protected $huashu = [
        '在的!',
        '请说,有什么问题?今年多大年龄了?',
        '你好!',
        '或者留个微信,我朋友圈有相关信息'
    ];
    protected $pre = [];
    /**
     * 获取user_info
     * @param $uid
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserInfo($uid)
    {
        if (!isset($this->user_info[$uid])){
            $this->user_info[$uid] = Db::table("os_admin_user")->where("id",$uid)->find();
            if (!$this->user_info[$uid]){
                exit("/** error user_info */");
            }
        }

        return  $this->user_info[$uid];
    }

    /**
     * 获取指定uid的info信息
     * @param $uid
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getInfo($sn)
    {
        $uid = unlock($sn);
        if(!$uid) {
            exit("/** error sn */");
        }
        if (!isset($this->info[$uid])){
            $info = Db::table("os_shb")->where("uid",$uid)->find();
            //商务通 引导页面的 医生 头像 绝对地址
            $info["doctor_pic"] = $info["doctor_pic"]?$info["doctor_pic"]:'/shb/images/doctor.jpg';
            $info["doctor_pic"] = Env::get('cdn_host').$info["doctor_pic"];
            
         
            //商务通 引导页面的 访客 头像 绝对地址
            $info["kehu_pic"] =$info["kehu_pic"]?$info["kehu_pic"]:'/shb/images/user_head_img.jpg';
            $info["kehu_pic"] = Env::get('cdn_host').$info["kehu_pic"];
            
            $info["duihua_arr"] = json_decode($info["duihua_arr"],true);
            if (!$info["duihua_arr"]){
                $info["duihua_arr"] = [];
            }
            $info["sn"] = $sn;
            $info["pre"] = $this->getPre($uid,$info["swt_id"]);
            $this->info[$uid] = $info;

            if (!$this->info[$uid]){
                exit("/** error uid */");
            }
        }

        return  $this->info[$uid];
    }

    protected function _initialize()
    {
        parent::_initialize();

    }

    /**
     * 拦截器 拦截IP 地域 过期等等
     * @param $sn
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function interceptor($sn)
    {
        $uid = unlock($sn);
        $user_info = $this->getUserInfo($uid);

        //此处可以发送信息给指定的人

        //用户到期
        if($user_info["endtime"] - time() < 0){
            die('/**die end*/');
        }

        $info = $this->getInfo($sn);
        //时间段
        $info["times"] = json_decode($info["times"],true);
        if (is_array($info["times"])){
            if(!checkTime($info["times"])){
                echo "/**die time*/";
                exit();
            }
        }

        //天机1
        $ip = getRealIp();
        $dis_ips = json_decode($info["ips"],true);
        if (is_array($dis_ips)){
            if(count($dis_ips) > 30){
                $dis_ips = array_slice($dis_ips,0,30);
            }
            if( in_array($ip,$dis_ips) ){
                echo "/**die ip*/";
                exit();
            }
        }

        // try{
        //     //地域
      
        //     $ipInfo = getIpInfo($ip);
        //     $info["areas"] = json_decode($info["areas"],true);
        //     dump($info["areas"]);
        //     die();
        //     if (is_array($info["areas"])){
        //         if($ipInfo["province"]){
        //             if( !in_array($ipInfo["province"],$info["areas"]) ){
        //                 exit("/**die area*/");
        //             }
        //         }
        //     }
        // }catch(Exception $e){

        // }


    }

    protected function getPre($uid,$swt_id){
        if(isset($this->pre[$uid])){
            return $this->pre[$uid];
        }else{

            preg_match("/[A-Za-z]*/",$swt_id,$pre);
    
            if (!isset($pre[0]) || empty($pre[0])){
                exit("/** error swt_id */");
            }else{
                $pre = strtolower($pre[0]);
            }

            $this->pre[$uid] = $pre;
            return $pre;
        }

    }

    /**
     * 升话宝引导页源码
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function shb_ydy_page(Request $request)
    {
        if (!$request->has('sn')){
            exit("/**  error no sn */");
        }
        $sn = $request->get("sn");
    
        $data = $this->getInfo($sn);

        return $this->fetch('ydy/shb_ydy_page',$data);
    }


    /**
     * 下载升话宝着陆页面
     * @param Request $request
     */
    public function down_shb_files(Request $request)
    {
        $info = $this->getInfo($request->get("sn"));

        $paths = [
            "doctor_pic" => $info["doctor_pic"],
            "kehu_pic" => $info["kehu_pic"],
            "yy_pic" => $info["yy_pic"],
            "yyhjtp" => $info["yyhjtp"]
        ];

        $res = get_file_json($paths);  
        
        $info = $res + $info;

        $index = $this->fetch("down/index",$info);
        file_put_contents(ROOT_PATH."/public/down/".$info["sn"],$index);
        $arr = [];
        $arr["index.html"] = Env::get("cdn_host")."/down/".$info["sn"];
        $arr["wechat.png"] = Env::get("cdn_host")."/down/wechat.png";
        $arr["wechat.gif"] = Env::get("cdn_host")."/down/wechat.gif";

        foreach($res as $val){
            $arr[$val["key"]] = $val["value"];
        }
        $arr = [
            "code"=> 0,
            "msg" => "",
            "resource" =>$arr
        ];
        echo json_encode($arr);

    }

    /**
     * 升话宝着陆页js代码interceptor
     * @param $sn
     * @return mixed
     */
    public function zly_shb_js($sn)
    {
        $this->interceptor($sn);

        $data = $this->getInfo($sn);

        return $this->fetch("ydy/js",$data );
    }

    /**
     * 着陆页升话宝Api
     * @param Request $request
     */
    public function zly_shb_api(Request $request)
    {
        $post = file_get_contents("php://input");
        $data = json_decode( html_entity_decode($post) ,true);

        if (empty($data)) {
            exit("/** error empty post */");
        }

        $info = $this->getInfo($data["sn"]);

        $info += $data; 
        $info["keyword"] = urlencode($info["wd"]);
        foreach($info["duihua_arr"] as &$val){
            $val = keyword_replace($val,$info["wd"]);
        }
        $html= $this->fetch('ydy/api/html',$info);
        $js = $this->fetch('ydy/api/js',$info);

        return json_encode([
            'code' => 0,
            'do' => $js,
            'html' => $html
        ]);
    }

    /**
     * 客服软件升话宝JS代码
     * @param Request $request
     */
    public function soft_shb_js($sn)
    {
        $this->interceptor($sn);
        $info = $this->getInfo($sn);
        return $this->fetch("soft/js",$info);
    }

    /**
     * 客服软件升话宝Api
     * @param Request $request
     */
    public function soft_shb_api(Request $request)
    {
        $post = file_get_contents("php://input");
        $data = json_decode( html_entity_decode($post) ,true);

        if (empty($data)) {
            exit("/** error empty post */");
        }

        $info = $this->getInfo($data["sn"]);
        foreach($info["duihua_arr"] as &$val){
            $val = keyword_replace($val,$data["wd"]);
        }
        $js = $this->fetch('soft/api/js',$info);



        return json_encode([
            'code' => 0,
            'msg'  => '',
            'do' => $js
        ]);
    }

}
